<template>
  <div class="layout-warpper content">
    <div class="layout-header content-header">
      <!--
        label-width="80px" -->
      <el-form ref="formSearch" :model="formSearch" :rules="rules" :inline="true" class="form-search" size="normal">
        <el-form-item label="行业类别">
          <el-cascader
            v-model="formSearch.industry"
            option-max-width="100px"
            class="ui-w240"
            :props="{ multiple: true }"
            collapse-tags
            :collapse-tags-max-num="1"
            :tooltip-max-width="200"
            tooltip-effect="light"
            :options="TASKOBJ.industryTypeAndIndustry"
            @change="industryTypeAndIndustryFn"
          />
        </el-form-item>
        <el-form-item label="交易方式">
          <!-- {{ tenderModeData }} -->
          <!-- {{ formSearch.tenderMode }} -->
          <el-cascader
            v-model="formSearch.tenderMode"
            option-max-width="100px"
            class="ui-w150"
            clearable
            :tooltip-max-width="200"
            tooltip-effect="light"
            :options="tenderModeData"
            @change="submitSearchFn"
          />
        </el-form-item>
        <!-- <el-form-item label="交易方式">
          <el-select
            v-model="formSearch.industry"
            class="ui-w120"
            value-key=""
            placeholder="请选择"
            clearable
            filterable
            @change="typeChangeFn"
          >
            <el-option
              v-for="item in industryTypeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="资审方式">
          <el-cascader
            v-model="formSearch.status"
            option-max-width="300px"
            class="ui-w120"
            clearable
            :options="TASKOBJ.qualificationExamMethods"
            @change="submitSearchFn"
          />
        </el-form-item>
        <el-form-item label="开标时间" prop="date">
          <el-date-picker
            v-model="formSearch.date"
            :clearable="true"
            type="daterange"
            align="right"
            style="width: 240px"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="handleSearchFn"
          />
        </el-form-item>
        <el-form-item label="" prop="keyWord">
          <!-- clearable -->
          <el-input
            v-model.trim="formSearch.keyWord"
            style="background: #1890ff"
            placeholder="项目/标段/名称/编号"
            class="ui-w320"
            @keydown="submitSearchFn"
          >
            <el-button slot="append" type="primary" icon="el-icon-search" @click="submitSearchFn" />
            <!-- <template slot="append"
              ><el-button type="primary" size="default" @click="submitSearchFn">
                <i class="el-input__icon el-icon-search"></i>
              </el-button>
            </template> -->
          </el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
        </el-form-item> -->
      </el-form>
    </div>
    <div class="layout-body">
      <task-table
        :table-data="tableTaskList"
        :t-a-s-k-o-b-j="TASKOBJ"
        :page-size="pageObj.pageSize"
        :current-page="pageObj.currentPage"
        :selection="false"
        :witness-link-code="'witnessing'"
        @pagination="() => subtaskListFn()"
      />
    </div>
    <!-- 分页 -->
    <div class="layout-footer ui-pt5">
      <!-- {{ pageObj.total + " " + pageObj.pageSize }} -->
      <pagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :page-sizes="pageObj.pageSizes"
        @pagination="() => subtaskListFn()"
      />
    </div>
    <!-- 见证记录 -->
    <!-- <WitnessRecord
      :show="recordShow"
      :type="recordType"
      :id="subtaskRow.witnessSubTaskId"
      :data="recordData"
      :initData="TASKOBJ"
      @close="recordCloseFn"
      @submit="recordSubmitFn"
    /> -->
    <!-- 取消见证 -->
    <el-dialog
      title="取消见证"
      :visible.sync="cancelVisible"
      width="500px"
      class="cancel-dialog"
      @close="cancelCloseFn"
    >
      <div class="info">
        <i class="el-icon-warning" />
        取消见证后该项目将从任务列表中清除，且该项目所有见证数据将清空， 确定要取消吗？
      </div>
      <el-form
        ref="cancelForm"
        class="ui-mt10"
        :model="cancelForm"
        :rules="cancelRules"
        label-width="80px"
        :inline="false"
        size="normal"
        on-submit="return false;"
      >
        <el-form-item label="验证码" required prop="code">
          <el-input v-model="cancelForm.code" class="ui-w100" />
          <span title="看不清？换一张" @click="refreshCode">
            <s-identify class="ui-w120" :identify-code="identifyCode" />
          </span>
          <el-button type="text" size="default" @click="refreshCode">看不清？换一张</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" :loading="cancelLoading" @click="cancelSubmitFn">确定</el-button>
        <el-button @click="cancelVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  // import ExpertList from "./expertList.vue";
  // import expertSignIn from "./expertSignIn.vue";
  import _ from "lodash";
  // taskList, subtaskList,
  import { moduleInit, taskCancel, myWitnessList } from "../../../../api/api.js";
  // import TopStatus from "../../../../components/TopStatus.vue";
  // import AssignDialog from "../../../../components/dialog/AssignDialog.vue";
  // import WitnessRecord from "../../../../components/dialog/WitnessRecord.vue";
  import TaskTable from "../TaskTable";
  import SIdentify from "../../../../components/sidentify.vue";
  import { isOneH } from "@/utils/utils";
  export default {
    components: {
      // TopStatus,
      // AssignDialog,
      SIdentify,
      // WitnessRecord,
      TaskTable
    },
    data() {
      // 验证码校验
      const validateCode = (rule, value, callback) => {
        if (value === "" || typeof value === "undefined") {
          callback(new Error("验证码不能为空"));
        } else if (value !== this.identifyCode) {
          callback(new Error("验证码不正确"));
        } else {
          callback();
        }
      };
      return {
        multipleTaskSelection: [],
        multipleSubTaskSelection: [],
        activeName: "expertList",
        TASKOBJ: {},
        tenderModeData: [],
        industryTypeArr: [],
        liveStatusArr: [],
        roomNameList: [],
        formSearch: {
          date: [this.$moment(new Date()).format("yyyy-MM-DD"), this.$moment(new Date()).format("yyyy-MM-DD")],
          keyWord: "",
          industry: [],
          tenderMode: [],
          status: ""
        },
        rules: {
          // date: [{ required: true, message: "日期不能为空", trigger: "blur" }],
          // keyWord: [{ required: true, message: "key不能为空", trigger: "blur" }],
        },
        currentWitness: {},
        identifyCode: "",
        cancelLoading: false,
        cancelVisible: false,
        cancelForm: {},
        cancelRules: {
          // reason: [
          //   { required: true, message: "停止原因不能为空", trigger: "blur" },
          // ],
          code: [
            {
              validator: validateCode,
              trigger: "blur"
            },
            { required: true, message: "验证码不能为空", trigger: "change" }
          ]
        },
        tableTaskList: [],
        tableData: [],
        recordShow: false,
        subtaskRow: {},
        recordData: [],
        recordType: "random",
        assignShow: false,
        assignData: [],
        assignType: "random",
        pageObj: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [10, 20, 30]
        },
        pageSizes: [10, 20, 30],
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              }
            }
          ]
        }
      };
    },
    // 监听属性 类似于data概念
    computed: {
      nettyPendData() {
        return this.$websocketNettyPend.getters.pendData;
      }
    },
    // 监控data中的数据变化
    watch: {
      nettyPendData: {
        handler(newVal) {
          console.log("addtask netty ws消息变化===============nettyPendData=", newVal);
          if (!newVal || !newVal.data) {
            return;
          }
          // console.log("newVal.witnessRecordList", newVal);
          console.log("nthis.tableTaskList", this.tableTaskList);
          // 可以调接口查出最新的数据，更新表格
          Object.keys(newVal.data).forEach(async (key, index) => {
            if (!index) {
              const data = await this.subtaskListFn(newVal.data[key].projectCode);
              console.log("data", data);
              this.tableTaskList.forEach((item, indexB) => {
                if (data.data.length) {
                  if (item.projectCode === newVal.data[key].projectCode) {
                    this.$set(
                      this.tableTaskList[indexB],
                      "bidsectionInfoList",
                      this.transferList(data.data)[0].bidsectionInfoList
                    );
                  }
                } else {
                  // this.$set(this.tableTaskList[indexB], "bidsectionInfoList", []);
                  // if (!this.tableTaskList[indexB].bidsectionInfoList.length) {
                  this.tableTaskList.splice(indexB, 1);
                  // }
                }
              });
            }
          });
          // 每次处理1个项目的待定
          // 见证中、暂停见证、待见证、已完成 需要分别处理
        },
        immediate: true
      }
    },
    async created() {
      await this.moduleInitFn();
      // await this.handleSearchFn();
    },
    methods: {
      // 验证码开始
      refreshCode() {
        this.identifyCode = this.makeCode("1234567890", 4);
      },
      makeCode(o, l) {
        let code = "";
        for (let i = 0; i < l; i++) {
          code += o[this.randomNum(0, o.length)];
        }
        return code;
      },
      randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
      },
      // 验证码结束
      // 主任务表格多选
      handleTaskSelectionChangeFn(val) {
        this.multipleTaskSelection = val;
        console.log("val", val);
        // this.assignData = val;
      },
      // 子任务表格多选
      handleSubTaskSelectionChangeFn(val) {
        console.log("val", val);
        this.multipleSubTaskSelection = val;
        this.assignData = val;
      },
      // table 展开收起
      expandChangeFn(row) {
        console.log("row", row);
        if (!row.children) {
          // const o = {
          //   witnessTaskId: row.witnessTaskId
          // };
          let index = "";
          this.tableData.some((item, i) => {
            if (item.witnessTaskId === row.witnessTaskId) {
              index = i;
            }
          });
          console.log("index", index);
          // this.subtaskListFn(o, index);
          this.subtaskListFn();
        }
      },
      // 取消见证-提交
      cancelSubmitFn() {
        this.$refs["cancelForm"].validate((valid) => {
          if (valid) {
            if (this.cancelForm.code === this.identifyCode) {
              this.cancelLoading = true;
              console.log("111");
              this.taskCancelFn();
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      // 取消见证-提交
      cancelCloseFn() {
        this.cancelVisible = false;
      },
      // 取消见证接口 ---接口需要改动 by link 20211110
      async taskCancelFn() {
        try {
          const p = {
            witnessSubTaskId: this.currentWitness.witnessSubTaskId
          };
          const res = await taskCancel(p);
          if (res.success) {
            this.cancelVisible = false;
            this.cancelLoading = false;
            this.$message({
              type: "success",
              message: res.message || "操作成功",
              single: true
            });
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 行业类型转文字
      industryFn(val) {
        const array = this.TASKOBJ.industryTypeAndIndustry;
        const obj = this.findArrayFn(array, val) || {};
        return obj.label;
      },
      randomAssignFn() {
        this.assignType = "random";
      },
      orientationAssignFn() {
        this.assignShow = true;
        this.assignType = "orientation";
        // this.assignData = [];
      },
      batchApproveFn() {},
      assignSubmitFn() {},
      assignCloseFn() {
        this.assignShow = false;
      },
      recordSubmitFn() {},
      recordCloseFn() {
        this.recordShow = false;
      },
      indexFn(index) {
        return index + 1 + (this.pageObj.currentPage - 1) * this.pageObj.pageSize;
      },
      async moduleInitFn() {
        const p = { moduleName: "TASK" };
        try {
          const res = await moduleInit(p);
          if (res.success) {
            this.TASKOBJ = res.data;
            for (const key in res.data.industryType) {
              if (Object.hasOwnProperty.call(res.data.industryType, key)) {
                const item = res.data.industryType[key];
                this.industryTypeArr.push({
                  label: item,
                  value: key
                });
              }
            }
            this.roomNameList = res.data.roomNameList;
            for (const key in res.data.liveStatus) {
              if (Object.hasOwnProperty.call(res.data.liveStatus, key)) {
                const item = res.data.liveStatus[key];
                this.liveStatusArr.push({
                  label: item,
                  value: key
                });
              }
            }
            this.industryTypeAndIndustryFn([]);
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      async handleSearchFn() {
        this.pageObj.total = 0;
        this.pageObj.currentPage = 1;
        await this.subtaskListFn();
        // await this.taskListFn();
      },
      // 管理员任务列表 /gdw/witness/subtask/list
      async subtaskListFn(projectCode) {
        // projectCode 项目code 用于待定更新后，刷新数据用
        // currentPage // 当前页数
        // endTime // 结束时间
        // industry // 枚举值: QT
        // industryType // 枚举值: GCJS,ZFCG,CQJY,TDJY,YPCG
        // pageSize  // 每页条数
        // search // 关键字搜索
        // startTime // 起始时间
        // tenderMode // 枚举值: PUBLIC_BIDDING,INVITE_BIDDING
        // witnessSubTaskStatus // 枚举值: UNASSIGNED,ASSIGNED,WITNESSING,WITNESS_FINISHED,WITNESS_UN_REVIEWED,WITNESS_PASS
        try {
          const obj = {};
          const industryList = [];
          const industryTypeList = [];
          this.formSearch.industry.forEach((item) => {
            if (!obj[item[0]]) {
              obj[item[0]] = 1;
              if (item[0] !== null) {
                industryTypeList.push(item[0]);
              }
            }
            if (item[1] !== null) {
              industryList.push(item[1]);
            }
          });
          const tenderModeList = this.formSearch.tenderMode;
          const p = {
            pageNum: this.pageObj.currentPage, // 当前页数
            pageSize: this.pageObj.pageSize, // 每页条数
            witnessStatus: "ING_WITNESS",
            tenderModeList, // 交易方式
            industryList, // 行业类型
            industryTypeList, // 行业类型
            qualificationExamMethod: this.formSearch.status[0], // 资审方式
            search: this.formSearch.keyWord // 搜索
          };
          // console.log("this.formSearch.date", this.formSearch.date);
          if (this.formSearch.date && this.formSearch.date.length) {
            p.startDate = `${this.formSearch.date[0]} 00:00:00`; // 起始时间
            p.endDate = `${this.formSearch.date[1]} 23:59:59`; //
          }
          if (projectCode) {
            p.projectCode = projectCode;
          } else {
            this.tableTaskList = [];
            this.pageObj.total = 0;
          }
          const res = await myWitnessList(p);
          if (res.success) {
            if (p.projectCode) {
              return res.data;
            }
            if (res.data.data.length === 0 && this.pageObj.currentPage !== 1) {
              this.pageObj.currentPage = 1;
              this.$nextTick(() => {
                this.subtaskListFn();
              });
              return;
            }
            this.tableTaskList = this.transferList(res.data.data);
            console.log("this.tableTaskList", this.tableTaskList);
            this.pageObj.total = res.data.pageBean.count;
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      roomIdchangeFn() {
        this.handleSearchFn();
      },
      typeChangeFn() {
        this.handleSearchFn();
      },
      statusChangeFn() {
        this.handleSearchFn();
      },
      recordClickFn({ row }) {
        console.log("row", row);
        this.subtaskRow = row;
        this.recordShow = true;
      },
      updateClickFn() {},
      enterClickFn() {},
      cancelWitnessFn({ row }) {
        this.cancelVisible = true;
        this.currentWitness = row;
        console.log("row", row);
        this.refreshCode();
      },
      detailClickFn() {},
      showPdfWitnessFn() {},
      industryTypeAndIndustryFn(val) {
        const obj = {};
        this.TASKOBJ.industryTypeAndTenderMode.forEach((item) => {
          if (item.children) {
            obj[item.value] = item.children.map((itemB) => ({
              label: itemB.label,
              value: itemB.value
            }));
          }
        });
        const o2 = {};
        this.tenderModeData = [];
        if (!val.length) {
          for (const key in obj) {
            this.tenderModeData = this.tenderModeData.concat(obj[key]);
          }
        } else {
          val.forEach((item) => {
            if (obj[item[0]] && !o2[item[0]]) {
              o2[item[0]] = 1;
              this.tenderModeData = this.tenderModeData.concat(obj[item[0]]);
            }
          });
        }
        this.tenderModeData = _.uniqWith(this.tenderModeData, _.isEqual);
        this.submitSearchFn();
      },
      submitSearchFn() {
        console.log("formSearch.industry", this.formSearch.industry);
        this.handleSearchFn();
        // this.$refs["formSearchFn"].submit();
        // this.$refs["formSearch"].validate((valid) => {
        //   if (valid) {
        //     // alert("submit!");
        //   } else {
        //     console.log("error submit!!");
        //     return false;
        //   }
        // });
      },
      // 将后端传递的数据结构进行转化
      transferList(list) {
        let startAllButton;
        const date = new Date()
        for (const item of list) {
          startAllButton = new Set();
          let count = 0;
          const bidListLength = item.bidsectionInfoList.length;
          item["bidsectionInfoListCopy"] = [];
          for (let j = 0; j < bidListLength; j++) {
            const { length } = item.bidsectionInfoList[j].operData.result;
            const { operData } = item.bidsectionInfoList[j];
            for (let i = 0; i < length; i++) {
              let obj = {};
              for (const key in item["bidsectionInfoList"][j]) {
                obj[key] = item["bidsectionInfoList"][j][key];
                delete obj["operData"];
              }
              obj = { ...obj, ...operData["result"][i]["data"], pageOpers: operData["result"][i]["pageOpers"] };
              item["bidsectionInfoListCopy"][count] = obj;
              if(!isOneH(obj.bidEvaluationStartTime, date)){
                obj.evaluationAddress = '**'
              }
              count++;
              startAllButton.add(obj.witnessLinkCode)
            }
          }
          item["bidsectionInfoList"] = item["bidsectionInfoListCopy"];
          delete item["bidsectionInfoListCopy"];
          Array.from(startAllButton).forEach(startAllButtonItem => {
            item[`START_ALL_${startAllButtonItem}`] = true
          })
        }
        return list;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .content {
    width: 100%;
    height: 100%;
    //采用flex布局，代替calc属性 by link 20211020
    display: flex;
    flex-flow: column;
  }
  .content-header {
    margin-top: 10px;
  }
  .form-search {
    padding-top: 10px;
    padding-left: 20px;
    background: #efefef;
    margin-bottom: 10px;
  }
  .tag-list {
    padding: 0 10px 10px;
  }
  .task-status {
    span {
      background: #ccc;
      border-radius: 50%;
      display: inline-block;
      margin-right: 4px;
      width: 24px;
      height: 24px;
      font-size: 14px;
      text-indent: 5px;
      line-height: 24px;
      overflow: hidden;
      color: #fff;
    }
    .WITNESSING {
      background: $WITNESSING;
    }
    .WITNESS_FINISHED {
      background: $WITNESS_FINISHED;
    }
    .ASSIGNED {
      background: $ASSIGNED;
    }
    .UNASSIGNED {
      background: $UNASSIGNED;
    }
  }
  .cancel-dialog {
    .info {
      padding-left: 28px;
      position: relative;
      i {
        position: absolute;
        top: 0;
        left: 0;
        color: #e6ad00;
        font-size: 18px;
        vertical-align: top;
      }
    }
  }
</style>
